package edu.suda.xsap.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import edu.suda.xsap.common.Jwt;
import edu.suda.xsap.common.Result;
import edu.suda.xsap.entity.Employee;
import edu.suda.xsap.entity.vo.LoginVo;
import edu.suda.xsap.service.EmployeeService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/*********************
 * 生成验证码的控制器
 */
@RestController
@RequestMapping("/captcha")
@Slf4j
public class CaptchaController {
@Autowired
private EmployeeService employeeService;



    @GetMapping("/arithmetic")
    public void generateArithmeticCaptcha(HttpServletRequest request,
                                          HttpServletResponse response)throws IOException {
        log.debug("==>生成数字计算类的验证码，指定响应头");
        // 指定响应头
        setHeader(response);
        // 生成验证码对象， 三个参数分别是宽、高、位数, ArithmeticCaptcha默认位数是2
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48, 3);
        log.debug("==>验证码的宽为{},高为{},位数是：{}", 130, 48, 3);
        String arithmeticString = captcha.getArithmeticString();
        log.debug("==> 本次数字计算验证码表达式：{}", arithmeticString);
        String text = captcha.text();
        log.debug("==> 本次数字计算验证码的结果是:{}", text);
        //验证码存入session
        request.getSession().setAttribute("verifyCode",text);
        //输出图片流
        captcha.out(response.getOutputStream());
    }

    private void setHeader(HttpServletResponse response) {
        response.setHeader("Cache-Control","no-store");
        response.setHeader("Pragma","no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/gif");
    }

    /**axios.post("/api/captcha/login",loginForm.value**/
    /***
     * const loginForm = ref({
     *);*/
    @PostMapping("/login")
    public Result validateArithmeticCaptcha(HttpServletRequest request,
                                          HttpServletResponse response,
                                          @RequestBody LoginVo loginVo) throws IOException {
        Result result = Result.success();
        HttpSession session = request.getSession(false); // 获取 session
        String userInput = loginVo.getCaptcha();
        String phone = loginVo.getPhone();
        String password = loginVo.getPassword();
        if (employeeService.findByPhone(phone) == null) {
            System.out.println("用户不存在");
            result.setCode(400);
            result.setMessage("用户不存在");
            return result;
        }
        if (!employeeService.findByPhone(phone).equals(password)) {
            System.out.println("密码错误");
            result.setCode(400);
            result.setMessage("密码错误");
            return result;
        }
        if (session == null) {
            result.setCode(400);
            result.setMessage("验证码不存在");
            return result;
        }

        String correctVerifyCode = (String) session.getAttribute("verifyCode");
        if (correctVerifyCode == null) {
            result.setCode(400);
            result.setMessage("验证码不存在");
            return result;
        }

        // 比较用户输入的验证码与正确的验证码
        if (userInput.equalsIgnoreCase(correctVerifyCode)) {
            // 验证码正确
            String token = Jwt.genAccessToken(phone);
            result.setCode(200);
            // 删除 session 中的验证码
            session.removeAttribute("verifyCode");
            //token存进请求头
            response.setHeader("Authorization",token);

        } else {
           result.setCode(400);
           result.setMessage("验证码错误");
        }
        return result;
    }


    /***captcha/register**/
    @PostMapping("/register")
    public Result register(@RequestBody Employee employee){
        try{
            employeeService.save(employee);
            return Result.success();
        }catch (Exception e){
            log.error("添加失败", e);
            return Result.failure(e.getMessage(), e);
        }

    }


}
